package com.douqu.game.activity.manager;

import com.alibaba.fastjson.JSONObject;
import com.bean.core.buffer.ByteBuffer;
import com.bean.core.util.TimeUtils;
import com.bean.core.util.Utils;
import com.douqu.game.activity.GameServer;
import com.douqu.game.activity.PrintUtils;
import com.douqu.game.activity.database.mapper.ActivityCampMapper;
import com.douqu.game.activity.database.mapper.ServerMergeMapper;
import com.douqu.game.activity.database.model.ActivityCampModel;
import com.douqu.game.activity.entity.camp.CampPlayer;
import com.douqu.game.activity.entity.camp.CampRecordPlayer;
import com.douqu.game.activity.entity.camp.MatchTeam;
import com.douqu.game.activity.entity.camp.MatchTempObject;
import com.douqu.game.activity.entity.e.E_PlayerStatus;
import com.douqu.game.activity.server.SpringContext;
import com.douqu.game.core.config.StableDataConfig;
import com.douqu.game.core.config.activity.CampRobotConfig;
import com.douqu.game.core.config.common.GoodsData;
import com.douqu.game.core.e.*;
import com.douqu.game.core.entity.activity.MatchBaseInfo;
import com.douqu.game.core.entity.activity.RankCamp;
import com.douqu.game.core.entity.activity.RankPlayer;
import com.douqu.game.core.entity.battle.BattleResultParamCamp;
import com.douqu.game.core.entity.battle.BattleResultParamCampSingle;
import com.douqu.game.core.factory.ConfigFactory;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.LoadUtils;
import com.douqu.game.core.util.LogUtils;

import javax.swing.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2018-03-08 14:29
 */
public class ActivityCampManager extends ActivityManager
{
    /**
     * 定时任务
     */
    private ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    /**
     * 匹配的线程
     */
    private ScheduledFuture matchFuture;

    private E_ActivityCampStatus status;

    public long todayEndTime;

    /**
     * 到活动开始还有多少时间
     */
    public int nextStartTime;

    /**
     * 到活动结束还有多少时间
     */
    public int nextEndTime;

    private ActivityCampModel activityCampModel;

    /**
     * 所有等待匹配的玩家(匹配成功后就会删除)
     */
    private Map<Integer, List<CampPlayer>> campPlayerMap = new ConcurrentHashMap<>();

    /**
     * 当前所有报名的玩家(复活次数没有后就会删除)
     */
    private List<CampPlayer> playerList = new CopyOnWriteArrayList<>();
    /**
     * 复活次数没有后就移动到这个集合里
     */
    private List<CampRecordPlayer> leavePlayerList = new CopyOnWriteArrayList<>();

    /**
     * 临时存储匹配记录,用来处理没有复活次数后再次报名没有地方获取匹配记录
     */
    private Map<String, List<String>> tempMatchListMap = new ConcurrentHashMap<>();

    /**
     * 匹配好的组
     */
    private List<MatchTeam> matchTeamList = new CopyOnWriteArrayList<>();

    /** 当前阵营排行 */
    private List<RankCamp> rankCampList;
    /** 当前玩家排行 */
    private List<RankPlayer> rankPlayerList;
    /** 最高连胜玩家 */
    private RankPlayer maxContinueWinPlayer;
    /** 最高击杀玩家 */
    private RankPlayer maxWinCountPlayer;
    /** 最高功勋玩家 */
    private RankPlayer maxExploitPlayer;

    public ActivityCampManager()
    {
        maxContinueWinPlayer = new RankPlayer();
        maxWinCountPlayer = new RankPlayer();
        maxExploitPlayer = new RankPlayer();

        rankCampList = new CopyOnWriteArrayList<>();
        rankPlayerList = new CopyOnWriteArrayList<>();

        status = E_ActivityCampStatus.FREE;
    }

    /**
     * 一秒运行一次的更新线程
     */
    public void update(int updateIntervalTime)
    {
        if(!GameServer.getInstance().isRunning() || activityCampModel == null || isLock())
            return;

        if(nextStartTime > 0)
        {
            nextStartTime -= updateIntervalTime;
            if(nextStartTime <= 0)
            {
                nextStartTime = 0;
                start(false);
            }
        }

        if(nextStartTime == 0 && GameServer.getInstance().getActivityCampManager().getStatus() == E_ActivityCampStatus.FREE)
        {
            //如果开服时已经在活动时间内，则直接开始
            start(true);
        }

        for(MatchTeam matchTeam : matchTeamList)
        {
            if(matchTeam.isStartBattle())
            {
                matchTeam.startBattle();

                removeMatchTeam(matchTeam);
                continue;
            }
            if(matchTeam.isOverdue())
            {
                LogUtils.error("匹配成功的人出现连接战斗不成功的异常 -> " + matchTeam + "   重新把玩家加入匹配列表");

                if(matchTeam.getPlayer().getBaseInfo().getServerId() != 0)
                {
                    addMatchPlayer(matchTeam.getPlayer().getBaseInfo(), E_ApplyCampActivityType.BATTLE_ERROR);
                }
                if(matchTeam.getTarget().getBaseInfo().getServerId() != 0)
                {
                    addMatchPlayer(matchTeam.getTarget().getBaseInfo(), E_ApplyCampActivityType.BATTLE_ERROR);
                }

                removeMatchTeam(matchTeam);
            }
        }

        if(nextEndTime > 0)
        {
            nextEndTime -= updateIntervalTime;
            if(nextEndTime <= 0)
            {
                nextEndTime = 0;
                end();
            }
        }

        if(status == E_ActivityCampStatus.CLEAR_ING)
        {
            if(DataFactory.currentTime - todayEndTime >= activityCampModel.getClearTime())
            {
                LogUtils.warn("结算完成，数据保存到文件，通知各主服务器可以领奖了!");

                PrintUtils.saveCampActivityRankInfo();

                status = E_ActivityCampStatus.FREE;
                initTime();
//                playerMap.clear();
                campPlayerMap.clear();
                playerList.clear();
                leavePlayerList.clear();
                matchTeamList.clear();

                GameServer.getInstance().sendActivityStatus(false, false);
            }
        }
    }


    public void clearRank()
    {
        rankPlayerList.clear();

        rankCampList.clear();

        //20180416根据策划方案 修改为历史数据只保存当天的，不保存历史最高
        maxContinueWinPlayer.clear();
        maxWinCountPlayer.clear();
        maxExploitPlayer.clear();
    }

    public void initRankCamp()
    {
        rankCampList.add(new RankCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE, 0));
        rankCampList.add(new RankCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE, 0));
        rankCampList.add(new RankCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_DARK_VALUE, 0));
    }

//    public void init()
//    {
//        long startTime = CampActivityFactory.getCampActivityStartTime();
//        final long currentTime = DataFactory.currentTime == 0 ? System.currentTimeMillis() : DataFactory.currentTime;
//        long endTime = CampActivityFactory.RUN_TIME + startTime;
//        if(currentTime >= startTime)
//        {
//            if(currentTime <= endTime)
//            {
//                nextStartTime = 0;
//                nextEndTime = (int) (endTime - currentTime);
//                index = TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
//            }
//            else
//            {
//                startTime += 24 * 60 * 60 * 1000;
//                nextStartTime = (int) (startTime - currentTime);
//                nextEndTime = nextStartTime + CampActivityFactory.RUN_TIME;
//
//                Calendar calendar = new GregorianCalendar();
//                calendar.setTimeInMillis(DataFactory.currentTime);
//                calendar.add(calendar.DATE, 1);
//                index = TimeUtils.getFormatTime(calendar.getTimeInMillis(), TimeUtils.YYYYMMDD);
//            }
//        }
//        else
//        {
//            nextStartTime = (int) (startTime - currentTime);
//            nextEndTime = nextStartTime + CampActivityFactory.RUN_TIME;
//            index = TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
//        }
//
//        //保证尾数取整
//        nextStartTime = nextStartTime / 1000 * 1000;
//        nextEndTime = nextEndTime / 1000 * 1000;
//
//        LogUtils.warn("初始化时间 -> nextStartTime:" + nextStartTime + ",nextEndTime:" + nextEndTime + ",index:" + index);
//    }

    public void initTime()
    {
        if(activityCampModel == null)
        {
            LogUtils.error("activityCampModel 为空，请检查!");
            System.exit(0);
            return;
        }

        try{
            long startTime = TimeUtils.getTimeByString(TimeUtils.getCurrentTime(TimeUtils.YYYY_MM_DD) + " " + activityCampModel.getStartTime().toString());

            final long currentTime = DataFactory.currentTime == 0 ? System.currentTimeMillis() : DataFactory.currentTime;
            int runTime = activityCampModel.getTotalTime();
            long endTime = runTime + startTime;
            if(currentTime >= startTime)
            {
                if(currentTime <= endTime)
                {
                    nextStartTime = 0;
                    nextEndTime = (int) (endTime - currentTime);
                    index = TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
                }
                else
                {
                    startTime += 24 * 60 * 60 * 1000;
                    nextStartTime = (int) (startTime - currentTime);
                    nextEndTime = nextStartTime + runTime;

                    Calendar calendar = new GregorianCalendar();
                    calendar.setTimeInMillis(DataFactory.currentTime);
                    calendar.add(calendar.DATE, 1);
                    index = TimeUtils.getFormatTime(calendar.getTimeInMillis(), TimeUtils.YYYYMMDD);
                }
            }
            else
            {
                nextStartTime = (int) (startTime - currentTime);
                nextEndTime = nextStartTime + runTime;
                index = TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
            }

            //保证尾数取整
            nextStartTime = nextStartTime / 1000 * 1000;
            nextEndTime = nextEndTime / 1000 * 1000;

            LogUtils.warn("初始化时间 -> nextStartTime:" + nextStartTime + ",nextEndTime:" + nextEndTime + ",index:" + index + " 并通知主服");

        }catch (Exception e){
            LogUtils.errorException(e);
        }

    }



    public void startUpdate()
    {
        if(activityCampModel == null)
            return;

        if(matchFuture != null)
            return;

        int curSeconds = Integer.parseInt(TimeUtils.getCurrentTime("ss"));
        int delay = curSeconds == 0 ? 0 : ((60 - curSeconds) * 1000);
        matchFuture = service.scheduleAtFixedRate(() -> {

            try{
                if(LoadManager.loading)
                {
                    LogUtils.info("正在更新配置文件,等待......");
                    int count = 0;
                    while(LoadManager.loading)
                    {
                        Thread.sleep(1000);

                        if(++count >= 30)
                        {
                            LogUtils.warn("30秒都还没更新完配置,可能是更新出错,请检查!");
                            break;
                        }
                    }
                }
                if(match())
                {
                    save();

                    LogUtils.info("完成一轮匹配，保存数据也完成---------------------------------");
                }
            }catch (Exception e){
                LogUtils.errorException(e);
            }

        }, delay + 1000, activityCampModel.getIntervalTime(), TimeUnit.MILLISECONDS);

        LogUtils.info("开启匹配线程-----------------" + activityCampModel.getIntervalTime());
    }

    public void loadFrom(byte[] data)
    {
        ByteBuffer buffer = new ByteBuffer(data);

        maxContinueWinPlayer.loadFrom(buffer);

        maxWinCountPlayer.loadFrom(buffer);

        maxExploitPlayer.loadFrom(buffer);

        RankPlayer rankPlayer = null;

        //当前玩家排行
        int size = buffer.readShort();
        for(int i = 0; i < size; i++)
        {
            rankPlayer = new RankPlayer();
            rankPlayer.loadFrom(buffer);
            rankPlayer.setServerName(GameServer.getInstance().getServerNameRemark(rankPlayer.getServerId()));

            rankPlayerList.add(rankPlayer);
        }

        //当前阵营排行
        RankCamp rankCamp = null;
        size = buffer.readByte();
        for(int i = 0; i < size; i++)
        {
            rankCamp = new RankCamp();
            rankCamp.loadFrom(buffer);
            rankCampList.add(rankCamp);
        }

        List<Integer> serverIdList = new ArrayList<>();

        tempIndex = buffer.readUTF();
        if(tempIndex.equals(index))
        {
            size = buffer.readInt();
            CampPlayer campPlayer = null;
            for(int i = 0; i < size; i++)
            {
                campPlayer = new CampPlayer();
                campPlayer.loadFrom(buffer);

                addMatchPlayer(campPlayer, E_ApplyCampActivityType.LOAD_DB);

                if(!serverIdList.contains(campPlayer.getPlayerBase().getServerId()));
                    serverIdList.add(campPlayer.getPlayerBase().getServerId());
            }
        }
        if(!serverIdList.contains(maxContinueWinPlayer.getServerId()))
            serverIdList.add(maxContinueWinPlayer.getServerId());
        if(!serverIdList.contains(maxWinCountPlayer.getServerId()))
            serverIdList.add(maxWinCountPlayer.getServerId());
        if(!serverIdList.contains(maxExploitPlayer.getServerId()))
            serverIdList.add(maxExploitPlayer.getServerId());

        if(!serverIdList.isEmpty())
        {
            Map<Integer, Integer> serverIdMap = new HashMap<>();
            //获取是否有合服的服务器ID
            ServerMergeMapper serverMergeMapper = SpringContext.getBean(ServerMergeMapper.class);
            Integer newServerId = null;
            for(Integer serverId : serverIdList)
            {
                newServerId = serverMergeMapper.findNewServerId(serverId);
                if(newServerId != null)
                    serverIdMap.put(serverId, newServerId);
            }

            if(!serverIdMap.isEmpty())
            {
                LogUtils.info("有合服的服务器 -> " + serverIdMap);

                if(serverIdMap.get(maxContinueWinPlayer.getServerId()) != null)
                    maxContinueWinPlayer.setServerId(serverIdMap.get(maxContinueWinPlayer.getServerId()));
                if(serverIdMap.get(maxWinCountPlayer.getServerId()) != null)
                    maxWinCountPlayer.setServerId(serverIdMap.get(maxWinCountPlayer.getServerId()));
                if(serverIdMap.get(maxExploitPlayer.getServerId()) != null)
                    maxExploitPlayer.setServerId(serverIdMap.get(maxExploitPlayer.getServerId()));

                for(CampPlayer campPlayer : playerList)
                {
                    if(serverIdMap.get(campPlayer.getPlayerBase().getServerId()) != null)
                        campPlayer.getPlayerBase().setServerId(serverIdMap.get(campPlayer.getPlayerBase().getServerId()));
                }

                LogUtils.info("修改服务器ID完成");
            }
        }
    }


    public void load()
    {
        ActivityCampMapper activityCampMapper = SpringContext.getBean(ActivityCampMapper.class);
        activityCampModel = activityCampMapper.find(id);
        if(activityCampModel != null)
        {
            LogUtils.info("阵营活动开始时间 -> " + activityCampModel.getStartTime());
            LogUtils.info("阵营活动持续时间 -> " + activityCampModel.getTotalTime()/60/1000 + "分钟");
            LogUtils.info("阵营活动匹配间隔 -> " + activityCampModel.getIntervalTime()/1000 + "秒");

            if(activityCampModel.getIntervalTime() == 0 || activityCampModel.getTotalTime() == 0)
            {
                JOptionPane.showMessageDialog(null, "加载activityCampModel错误,请检查->Id:" + id);
                System.exit(0);
                return;
            }

            initTime();

            clearRank();

            //其它数据
            byte[] info = activityCampModel.getInfo();
            if(info != null)
            {
                loadFrom(info);

                maxContinueWinPlayer.setServerName(GameServer.getInstance().getServerNameRemark(maxContinueWinPlayer.getServerId()));
                maxWinCountPlayer.setServerName(GameServer.getInstance().getServerNameRemark(maxWinCountPlayer.getServerId()));
                maxExploitPlayer.setServerName(GameServer.getInstance().getServerNameRemark(maxExploitPlayer.getServerId()));
            }

            if(rankCampList.isEmpty())
            {
                initRankCamp();
            }
        }
        else
        {
            LogUtils.error("加载数据错误,请检查->Id:" + id);
            JOptionPane.showMessageDialog(null, "加载数据错误,请检查->Id:" + id);
            System.exit(0);
        }
    }

    /**
     * 修改了配置，重新加载
     */
    public void reloadModelConfig()
    {
        lock = true;

        ActivityCampMapper activityCampMapper = SpringContext.getBean(ActivityCampMapper.class);
        activityCampModel = activityCampMapper.find(id);
        if(activityCampModel != null)
        {
            LogUtils.info("重新加载阵营活动开始时间 -> " + activityCampModel.getStartTime());
            LogUtils.info("重新加载阵营活动持续时间 -> " + activityCampModel.getTotalTime() / 60 / 1000 + "分钟");
            LogUtils.info("重新加载阵营活动匹配间隔 -> " + activityCampModel.getIntervalTime() / 1000 + "秒");

            if(status == E_ActivityCampStatus.FREE)
            {
                LogUtils.info("重新初始化时间!");
                initTime();
                GameServer.getInstance().sendActivityTime();
            }
            else
            {
                LogUtils.info("只有非活动运行期间才重新初始化时间!");
            }
        }

        lock = false;
    }

    public byte[] write()
    {
        ByteBuffer buffer = new ByteBuffer();

        maxContinueWinPlayer.writeTo(buffer);
        maxWinCountPlayer.writeTo(buffer);
        maxExploitPlayer.writeTo(buffer);

        buffer.writeShort(rankPlayerList.size());
        for(RankPlayer rankPlayer : rankPlayerList)
        {
            rankPlayer.writeTo(buffer);
        }

        buffer.writeByte(rankCampList.size());
        for(RankCamp rankCamp : rankCampList)
        {
            rankCamp.writeTo(buffer);
        }

        buffer.writeUTF(index);

        buffer.writeInt(playerList.size());
        for(CampPlayer campPlayer : playerList)
        {
            campPlayer.writeTo(buffer);
        }

        return buffer.getBytes();
    }

    public void save()
    {
        ActivityCampMapper activityCampMapper = SpringContext.getBean(ActivityCampMapper.class);

        activityCampModel.setInfo(write());

        activityCampMapper.update(activityCampModel);
    }

    public JSONObject updateRank(int serverId, BattleResultParamCampSingle resultParam)
    {
        JSONObject jsonObject = new JSONObject();
        if(maxWinCountPlayer.getValue() < resultParam.getCurWinCount())
        {
            maxWinCountPlayer.update(serverId, resultParam.getPlayerBase(), resultParam.getCurWinCount());
            maxWinCountPlayer.setServerName(GameServer.getInstance().getServerNameRemark(serverId));

            jsonObject.put(ConstantFactory.MAX_WIN_COUNT_PLAYER, maxWinCountPlayer);
        }

        if(maxExploitPlayer.getValue() < resultParam.getCurTotalExploit())
        {
            maxExploitPlayer.update(serverId, resultParam.getPlayerBase(), resultParam.getCurTotalExploit());
            maxExploitPlayer.setServerName(GameServer.getInstance().getServerNameRemark(serverId));

            jsonObject.put(ConstantFactory.MAX_EXPLOIT_PLAYER, maxExploitPlayer);
        }

        if(maxContinueWinPlayer.getValue() < resultParam.getCurMaxContinueWin())
        {
            maxContinueWinPlayer.update(serverId, resultParam.getPlayerBase(), resultParam.getCurMaxContinueWin());
            maxContinueWinPlayer.setServerName(GameServer.getInstance().getServerNameRemark(serverId));

            jsonObject.put(ConstantFactory.MAX_CONTINUE_WIN_PLAYER, maxContinueWinPlayer);
        }

//        LogUtils.info("更新后的排行 -> maxContinueWinPlayer:" + maxContinueWinPlayer);
//        LogUtils.info("更新后的排行 -> maxExploitPlayer:" + maxExploitPlayer);
//        LogUtils.info("更新后的排行 -> maxWinCountPlayer:" + maxWinCountPlayer);

        if(resultParam.getAddExploit() <= 0)
            return jsonObject;

        int rankValue = resultParam.getCurTotalExploit();
        boolean isAdd = true;
        if(rankPlayerList.size() == ConstantFactory.RANK_COUNT)
        {
            if(rankPlayerList.get(rankPlayerList.size()-1).getValue() > rankValue)
            {
                isAdd = false;
            }
        }

        if(isAdd)
        {
            boolean isIn = false;
            for(RankPlayer rankPlayer : rankPlayerList)
            {
                if(rankPlayer.getObjectIndex().equals(resultParam.getPlayerBase().getObjectIndex()))
                {
                    rankPlayer.update(serverId, resultParam.getPlayerBase(), rankValue);
                    isIn = true;
                    break;
                }
            }

            if(!isIn)
            {
                RankPlayer rankPlayer = new RankPlayer();
                rankPlayer.update(serverId, resultParam.getPlayerBase(), rankValue);
                rankPlayer.setServerName(GameServer.getInstance().getServerNameRemark(rankPlayer.getServerId()));
                rankPlayerList.add(rankPlayer);
            }

            rankPlayerList.sort(new Comparator<RankPlayer>() {
                @Override
                public int compare(RankPlayer o1, RankPlayer o2) {
                    return new Integer(o2.getValue()).compareTo(o1.getValue());
                }
            });

            if(rankPlayerList.size() > ConstantFactory.RANK_COUNT)
            {
                rankPlayerList.remove(rankPlayerList.get(rankPlayerList.size()-1));
            }
            else
            {
                jsonObject.put(ConstantFactory.RANK_PLAYER_LIST, rankPlayerList);
            }
        }

        if(resultParam.getAddExploit() > 0)
        {
            for(RankCamp rankCamp : rankCampList)
            {
                if(rankCamp.getCamp() == resultParam.getPlayerBase().getCamp())
                {
                    rankCamp.addValue(resultParam.getAddExploit());
                    break;
                }
            }

            rankCampList.sort(new Comparator<RankCamp>() {
                @Override
                public int compare(RankCamp o1, RankCamp o2) {
                    return new Integer(o2.getValue()).compareTo(o1.getValue());
                }
            });

            jsonObject.put(ConstantFactory.RANK_CAMP_LIST, rankCampList);
        }

        return jsonObject;
    }


    public void removeMatchTeam(MatchTeam matchTeam)
    {
        matchTeamList.remove(matchTeam);
    }


    public boolean match()
    {
        if(!GameServer.getInstance().isRunning())
            return false;

        if(status != E_ActivityCampStatus.RUN_ING)
        {
            LogUtils.info("活动没有开始或者已经结束!");
            return false;
        }

        if(!GameServer.getInstance().isHaveBattleServer())
        {
            LogUtils.error("战斗服务器没有开启,不能进行匹配操作");
            return false;
        }

        LogUtils.warn("开始新一轮匹配------------------------->");
        List<CampPlayer> otherCampList;
        List<CampPlayer> selfList;
        List<CampPlayer> matchPlayerList = null;
        List<CampRobotConfig> matchRobotList = null;
        StableDataConfig applyStable = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY, E_StableDataType.CAMP_ACTIVITY_APPLY.getCode());
        int lowLv = 10, highLv = 5, matchCount = 10;
        if(applyStable != null && applyStable.stringValue.length > 1)
        {
            lowLv = applyStable.stringValue[0];
            highLv = applyStable.stringValue[1];
        }
        StableDataConfig rewardStable = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY, E_StableDataType.CAMP_ACTIVITY_REWARD.getCode());
        matchCount = rewardStable.intValue < 1 ? 1 : rewardStable.intValue;

        MatchTempObject matchObject = null;
        long currentTime = DataFactory.currentTime == 0 ? System.currentTimeMillis() : DataFactory.currentTime;
        CampPlayer targetPlayer = null;
        MatchTeam matchTeam = null;
        for(Map.Entry<Integer, List<CampPlayer>> entry : campPlayerMap.entrySet())
        {
            selfList = entry.getValue();
            otherCampList = getOtherCampPlayerList(entry.getKey());

            for(CampPlayer player : selfList)
            {
                LogUtils.info("开始匹配 -> " + player);
                targetPlayer = null;
                if(player.getPlayerBase().getWinRate() <= 50)
                {
                    //匹配弱电脑(随机匹配在等级差区间的机器人)
                    matchRobotList = DataFactory.getInstance().getCampRobotList(1, player.getPlayerBase().getLv(), player.getPlayerBase().getLv()-lowLv);
                    matchObject = matchRobotList.isEmpty() ? null : new MatchTempObject(matchRobotList.get(Utils.getRandom(matchRobotList.size())));
                    LogUtils.debug("匹配弱的机器人 -> " + matchObject);
                }
                else
                {
                    //首先匹配真人,选择胜率接近的N个玩家,但要去除掉最近两局匹配过的玩家
                    matchPlayerList = new CopyOnWriteArrayList<>();
                    for(CampPlayer otherPlayer : otherCampList)
                    {
                        if(player.isCanMatch(otherPlayer))
                            matchPlayerList.add(otherPlayer);
                    }
                    if(!matchPlayerList.isEmpty())
                    {
                        //按照玩家跟自己的胜率相差最小的排序
                        Collections.sort(matchPlayerList, new Comparator<CampPlayer>() {
                            @Override
                            public int compare(CampPlayer o1, CampPlayer o2) {
                                return new Integer(Math.abs(o1.getPlayerBase().getWinRate()-player.getPlayerBase().getWinRate())).compareTo(Math.abs(o2.getPlayerBase().getWinRate()-player.getPlayerBase().getWinRate()));
                            }
                        });

                        LogUtils.debug("根据胜率差排序 -> " + matchPlayerList);

                        matchPlayerList = matchPlayerList.subList(0, Math.min(matchCount, matchPlayerList.size()));
                        targetPlayer = matchPlayerList.get(Utils.getRandom(matchPlayerList.size()));
                        matchObject = new MatchTempObject(E_MatchType.PLAYER, targetPlayer);
                        LogUtils.debug("匹配到真人 -> " + matchObject);
                    }
                    else
                    {
                        //没有符合条件的玩家，匹配高级机器人
                        matchRobotList = DataFactory.getInstance().getCampRobotList(2, player.getPlayerBase().getLv(), player.getPlayerBase().getLv()-highLv);
                        matchObject = matchRobotList.isEmpty() ? null : new MatchTempObject(matchRobotList.get(Utils.getRandom(matchRobotList.size())));
                        LogUtils.debug("匹配强机器人 -> " + matchObject);
                    }
                }

                if(matchObject == null)
                {
                    LogUtils.info("没有匹配到人 -> " + player);
                    continue;
                }

                if(matchObject.getMatchType() == E_MatchType.ROBOT)
                {
                    matchObject.getBaseInfo().setName(LoadUtils.getRandomPlayerName());
                    matchObject.getBaseInfo().setServerId(player.getPlayerBase().getServerId());
                    if(player.getPlayerBase().getCamp() == SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE)
                    {
                        matchObject.getBaseInfo().setCamp(Utils.getRandom(2) == 1 ? SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE : SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_DARK_VALUE);
                    }
                    else if(player.getPlayerBase().getCamp() == SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE)
                    {
                        matchObject.getBaseInfo().setCamp(Utils.getRandom(2) == 1 ? SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE : SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_DARK_VALUE);
                    }
                    else
                    {
                        matchObject.getBaseInfo().setCamp(Utils.getRandom(2) == 1 ? SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE : SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE);
                    }
                }

                matchTeam = addMatchTeam(matchObject.getMatchType(), matchObject.getMatchType() == E_MatchType.ROBOT ? E_BattleDetailType.PVE_SPAN_CAMP : E_BattleDetailType.PVP_SPAN_CAMP, player, matchObject);
                if(matchTeam == null)
                {
                    LogUtils.error("数据异常，重复匹配 -> target:" + matchObject);
                    continue;
                }

                LogUtils.warn(player + " -> 匹配结果 -> " + matchObject + " teamIndex:" + matchTeam.getId());
                LogUtils.info("---------------------------------------------------------");

                player.sendMatchSuccess(matchTeam.getId(), matchObject.getMatchType(), matchObject.getBaseInfo());
                player.setPlayerStatus(E_PlayerStatus.WAIT_BATTLE_START, currentTime);
                player.getPlayerBase().addMatch(matchObject.getBaseInfo().getObjectIndex());

                if(targetPlayer != null)
                {
                    targetPlayer.sendMatchSuccess(matchTeam.getId(), matchObject.getMatchType(), player.getPlayerBase());

                    targetPlayer.setPlayerStatus(E_PlayerStatus.WAIT_BATTLE_START, currentTime);
                    targetPlayer.getPlayerBase().addMatch(player.getPlayerBase().getObjectIndex());
                    otherCampList.remove(targetPlayer);
                    removeMatchPlayer(targetPlayer);

//                    LogUtils.info("真实玩家对战 -> " + player.getPlayerBase().getObjectIndex() + " VS " + matchObject.getBaseInfo().getObjectIndex() + " 对方阵营:" + targetPlayer.getPlayerBase().getCamp());
                }

                selfList.remove(player);
                removeMatchPlayer(player);
            }
        }

        return true;
    }

//    public boolean match()
//    {
//        if(!GameServer.getInstance().isRunning())
//            return false;
//
//        if(status != E_ActivityCampStatus.RUN_ING)
//        {
//            LogUtils.info("活动没有开始或者已经结束!");
//            return false;
//        }
//
//        if(!GameServer.getInstance().isHaveBattleServer())
//        {
//            LogUtils.error("战斗服务器没有开启,不能进行匹配操作");
//            return false;
//        }
//
//        LogUtils.warn("开始新一轮匹配------------------------->");
//        List<CampPlayer> otherCampList;
//        List<CampPlayer> selfList;
//        List matchList = null;
//        List<CampPlayer> lowerList, higherList;
//        StableDataConfig stableData = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY, E_StableDataType.CAMP_ACTIVITY_REWARD.getCode());
//        final int robotSize = stableData.intValue;
//        final long currentTime = DataFactory.currentTime;
//        MatchTeam matchTeam = null;
//        for(Map.Entry<Integer, List<CampPlayer>> entry : campPlayerMap.entrySet())
//        {
//            selfList = entry.getValue();
//            otherCampList = getOtherCampPlayerList(entry.getKey());
//            lowerList = new CopyOnWriteArrayList<>();
//            higherList = new CopyOnWriteArrayList<>();
//            for(CampPlayer campPlayer : otherCampList)
//            {
//                if(campPlayer.getPlayerBase().getWinRate() <= 50)
//                    lowerList.add(campPlayer);
//                else
//                    higherList.add(campPlayer);
//            }
//
//            for(CampPlayer player : selfList)
//            {
//                player.setPlayerStatus(E_PlayerStatus.MATCH_ING, currentTime);
//                LogUtils.info("开始匹配 -> " + player);
//                MatchTempObject matchObject = null;
//                E_BattleDetailType battleDetailType = null;
//
//                if(player.getPlayerBase().getWinRate() <= 50)
//                {
//                    //直接从机机器人库里取
//                    matchList = DataFactory.getInstance().getCampRobotList(1);
////                    LogUtils.debug("胜率小于等于50,直接匹配机器人");
//                }
//                else
//                {
//                    List<MatchTempObject> matchTempObjectList = new CopyOnWriteArrayList<>();
//                    List<CampRobotConfig> robotList = DataFactory.getInstance().getCampRobotList(2);
//                    //最近匹配过的不参与匹配
//                    for(CampPlayer otherPlayer : otherCampList)
//                    {
//                        if(player.isCanMatch(otherPlayer))
//                        {
//                            matchTempObjectList.add(new MatchTempObject(E_MatchType.PLAYER, otherPlayer));
//                        }
//                        else
//                        {
//                            higherList.remove(otherPlayer);
//                        }
//                    }
//                    if(otherCampList.size() < robotSize)
//                    {
////                        LogUtils.debug("总匹配人数小于50人,加入50个机器人");
//                        //匹配池人数小于50时,加入50个电脑
//                        Collections.shuffle(robotList);
//                        int count = Math.min(robotSize, robotList.size());
//                        for(int i = 0; i < count; i++)
//                        {
//                            matchTempObjectList.add(new MatchTempObject(robotList.get(i), Utils.getRandom(51)+50));
//                        }
//                    }
//                    if(matchTempObjectList.size() % 2 != 0)
//                    {
////                        LogUtils.debug("匹配的人数为单数,加入一个玩家机器人");
//                        //从其它大于50%胜率的玩家里随机取一个人数据,主将名字随机
//                        CampPlayer tempPlayer = null;
//                        if(!higherList.isEmpty())
//                            tempPlayer = higherList.get(Utils.getRandom(higherList.size()));
//                        else if(!lowerList.isEmpty())
//                            tempPlayer = lowerList.get(Utils.getRandom(lowerList.size()));
//
//                        if(tempPlayer == null)
//                            matchTempObjectList.add(new MatchTempObject(robotList.get(0), Utils.getRandom(51)+50));
//                        else
//                            matchTempObjectList.add(new MatchTempObject(E_MatchType.PLAYER_AI, tempPlayer));
//                    }
//
//                    Collections.sort(matchTempObjectList, new Comparator<MatchTempObject>() {
//                        @Override
//                        public int compare(MatchTempObject o1, MatchTempObject o2) {
//                            return new Integer(o1.getBaseInfo().getWinRate()).compareTo(o2.getBaseInfo().getWinRate());
//                        }
//                    });
//
//                    matchList = new ArrayList<>();
//                    List<MatchTempObject> list1 = new ArrayList<>();
//                    List<MatchTempObject> list2 = new ArrayList<>();
//                    for(MatchTempObject matchTempObject : matchTempObjectList)
//                    {
//                        if(matchTempObject.getBaseInfo().getWinRate() < player.getPlayerBase().getWinRate())
//                            list1.add(matchTempObject);
//                        else
//                            list2.add(matchTempObject);
//                    }
//                    list1.sort(new Comparator<MatchTempObject>() {
//                        @Override
//                        public int compare(MatchTempObject o1, MatchTempObject o2) {
//                            return new Integer(o2.getBaseInfo().getWinRate()).compareTo(o1.getBaseInfo().getWinRate());//从大到小
//                        }
//                    });
//                    list2.sort(new Comparator<MatchTempObject>() {
//                        @Override
//                        public int compare(MatchTempObject o1, MatchTempObject o2) {
//                            return new Integer(o1.getBaseInfo().getWinRate()).compareTo(o2.getBaseInfo().getWinRate());//从小到大
//                        }
//                    });
//
//                    int size1 = list1.size(), size2 = list2.size();
//                    if(size1 + size2 <= 20)
//                    {
//                        matchList.addAll(list1);
//                        matchList.addAll(list2);
//                    }
//                    else if(size1 <= 10)
//                    {
//                        matchList.addAll(list1);
//                        matchList.addAll(list2.subList(0, 20-size1));
//                    }
//                    else if(size2 <= 10)
//                    {
//                        matchList.addAll(list2);
//                        matchList.addAll(list1.subList(0, 20-size2));
//                    }
//                    else
//                    {
//                        matchList.addAll(list1.subList(0, 10));
//                        matchList.addAll(list2.subList(0, 10));
//                    }
//                }
//
//                if(matchList.isEmpty())
//                    continue;
//
//                Object finalObject = matchList.get(Utils.getRandom(matchList.size()));
//
//                if(finalObject instanceof MatchTempObject)
//                {
//                    matchObject = (MatchTempObject) finalObject;
//                    if(matchObject.getMatchType() == E_MatchType.PLAYER)
//                        battleDetailType = E_BattleDetailType.PVP_SPAN_CAMP;
//                    else if(matchObject.getMatchType() == E_MatchType.PLAYER_AI)
//                        battleDetailType = E_BattleDetailType.PVP_AI_SPAN_CAMP;
//                    else if(matchObject.getMatchType() == E_MatchType.ROBOT)
//                        battleDetailType = E_BattleDetailType.PVE_SPAN_CAMP;
//                }
//                else if(finalObject instanceof CampRobotConfig)
//                {
//                    matchObject = new MatchTempObject((CampRobotConfig)finalObject, player.getPlayerBase().getWinRate());//随机名字
//                    battleDetailType = E_BattleDetailType.PVE_SPAN_CAMP;
//                }
//
//                if(matchObject.getMatchType() != E_MatchType.PLAYER)
//                {
//                    //设置随机名字
//                    String randomName = LoadUtils.getRandomPlayerName();
////                    LogUtils.debug("设置随机名字 -> " + randomName);
//                    matchObject.getBaseInfo().setName(randomName);
//                }
//
//                if(matchObject.getBaseInfo().getCamp() == 0)
//                {
//                    if(player.getPlayerBase().getCamp() == SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE)
//                        matchObject.getBaseInfo().setCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE);
//                    else if(player.getPlayerBase().getCamp() == SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BLOODY_VALUE)
//                        matchObject.getBaseInfo().setCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_DARK_VALUE);
//                    else
//                        matchObject.getBaseInfo().setCamp(SGCommonProto.E_CAMP_TYPE.CAMP_TYPE_BRIGHT_VALUE);
//                }
//
//
//                if(matchObject == null)
//                    continue;
//
//                if(matchObject.getMatchType() == E_MatchType.ROBOT)
//                    matchObject.getBaseInfo().setServerId(player.getPlayerBase().getServerId());
//
//                matchTeam = addMatchTeam(matchObject.getMatchType(), battleDetailType, player, matchObject);
//                if(matchTeam == null)
//                {
//                    LogUtils.error("数据异常，重复匹配 -> target:" + matchObject);
//                    continue;
//                }
//
//                LogUtils.info("匹配结果 -> " + matchObject + " teamIndex:" + matchTeam.getId());
//                LogUtils.info("---------------------------------------------------------");
//
//                player.sendMatchSuccess(matchTeam.getId(), matchObject);
//
//                if(matchObject.getMatchType() == E_MatchType.PLAYER)
//                {
//                    matchObject.sendMatchSuccess(matchTeam.getId(), player.getPlayerBase());
//
//                    player.getPlayerBase().addMatch(matchObject.getBaseInfo().getObjectIndex());
//
//                    CampPlayer targetPlayer = getPlayer(matchObject.getBaseInfo().getObjectIndex());
//                    targetPlayer.setPlayerStatus(E_PlayerStatus.WAIT_BATTLE_START, currentTime);
//                    targetPlayer.getPlayerBase().addMatch(player.getPlayerBase().getObjectIndex());
//                    otherCampList.remove(targetPlayer);
//                    removeMatchPlayer(targetPlayer);
//
////                    LogUtils.info("真实玩家对战 -> " + player.getPlayerBase().getObjectIndex() + " VS " + matchObject.getBaseInfo().getObjectIndex() + " 对方阵营:" + targetPlayer.getPlayerBase().getCamp());
//                }
//                else if(matchObject.getMatchType() == E_MatchType.PLAYER_AI)
//                {
////                    LogUtils.info("玩家NPC -> " + player.getPlayerBase().getObjectIndex() + " VS " + matchObject.getBaseInfo().getObjectIndex());
//                }
//                else if(matchObject.getMatchType() == E_MatchType.ROBOT)
//                {
////                    LogUtils.info("机器人 -> " + player.getPlayerBase().getObjectIndex() + " VS " + matchObject.getBaseInfo().getObjectIndex());
//                }
//
//                selfList.remove(player);
//                removeMatchPlayer(player);
//
//                player.setPlayerStatus(E_PlayerStatus.WAIT_BATTLE_START, currentTime);
//            }
//        }
//
//        return true;
//    }

    public void addMatchPlayer(MatchBaseInfo baseInfo, E_ApplyCampActivityType type)
    {
        LogUtils.warn("玩家报名 -> " + baseInfo + " type -> " + type);
        List<CampPlayer> list = campPlayerMap.get(baseInfo.getCamp());
        if(list == null)
        {
            list = new CopyOnWriteArrayList<>();
            campPlayerMap.put(baseInfo.getCamp(), list);
        }

        CampPlayer player = getPlayer(baseInfo.getObjectIndex());
        if(player != null)
        {
            player.updatePlayerBase(baseInfo);
            player.setPlayerStatus(E_PlayerStatus.WAIT_MATCH, DataFactory.currentTime);

            list.remove(player);//删除旧的
            list.add(player);//添加新的
        }
        else
        {
            player = new CampPlayer(baseInfo);
            List<String> tempMatchList = tempMatchListMap.get(baseInfo.getObjectIndex());
            if(tempMatchList != null)
            {
                player.getPlayerBase().setMatchList(tempMatchList);
                tempMatchListMap.remove(baseInfo.getObjectIndex());
            }
            player.setPlayerStatus(E_PlayerStatus.WAIT_MATCH, DataFactory.currentTime);
            list.remove(player);//删除旧的
            list.add(player);//添加新的

            playerList.add(player);
            leavePlayerList.remove(new CampRecordPlayer(player.getPlayerBase().getObjectIndex()));
        }
    }

    public void addMatchPlayer(CampPlayer player, E_ApplyCampActivityType type)
    {
        if(player == null)
            return;

        LogUtils.warn("玩家报名 -> " + player.getPlayerBase() + " type -> " + type);
        List<CampPlayer> list = campPlayerMap.get(player.getPlayerBase().getCamp());
        if(list == null)
        {
            list = new CopyOnWriteArrayList<>();
            campPlayerMap.put(player.getPlayerBase().getCamp(), list);
        }

        player.setPlayerStatus(E_PlayerStatus.WAIT_MATCH, DataFactory.currentTime);
        list.remove(player);//删除旧的
        list.add(player);//添加新的

        if(playerList.contains(player))
            return;

        playerList.add(player);
        leavePlayerList.remove(new CampRecordPlayer(player.getPlayerBase().getObjectIndex()));

//        if(playerMap.get(player.getPlayerBase().getObjectIndex()) == null)
//        {
//            playerMap.put(player.getPlayerBase().getObjectIndex(), player);
//            playerList.add(player);
//        }
    }

    /**
     * 从匹配池删除
     * @param player
     */
    public void removeMatchPlayer(CampPlayer player)
    {
        List<CampPlayer> list = campPlayerMap.get(player.getPlayerBase().getCamp());
        if(list != null)
        {
            list.remove(player);
        }
    }

    /**
     * 从报名列表中删除
     * @param campPlayer
     */
    public void removePlayer(CampPlayer campPlayer)
    {
//        playerMap.remove(campPlayer.getPlayerBase().getObjectIndex());
        campPlayerMap.remove(campPlayer.getPlayerBase().getObjectIndex());
        playerList.remove(campPlayer);
        leavePlayerList.add(new CampRecordPlayer(campPlayer));

        //把匹配记录加入临时仓库,以便玩家再次报名时获取
        tempMatchListMap.put(campPlayer.getPlayerBase().getObjectIndex(), campPlayer.getPlayerBase().getMatchList());
    }

    public List<CampPlayer> getOtherCampPlayerList(int camp)
    {
        List<CampPlayer> list = new CopyOnWriteArrayList<>();
        for(Map.Entry<Integer, List<CampPlayer>> entry : campPlayerMap.entrySet())
        {
            if(camp != entry.getKey())
                list.addAll(entry.getValue());
        }
        return list;
    }

    public CampPlayer getPlayer(String playerIndex)
    {
        int index = playerList.indexOf(new CampPlayer(playerIndex));
        return index >= 0 ? playerList.get(index) : null;
    }

    public void start(boolean running)
    {
        if(activityCampModel == null)
        {
            LogUtils.error("activityCampModel 为空!");
            return;
        }
        if(matchFuture != null)
        {
            LogUtils.error("匹配已经开始");
            return;
        }

        if(status == E_ActivityCampStatus.RUN_ING)
        {
            LogUtils.error("活动已经在运行中!");
            return;
        }

        status = E_ActivityCampStatus.RUN_ING;

        startUpdate();

        LogUtils.warn("活动开始，通知所有参与的服务器 index -> " + index + " status -> " + status);

        if(nextEndTime >= activityCampModel.getTotalTime() || !tempIndex.equals(index) || !checkRankIsToday())
        {
            tempIndex = index;
            clearRank();
            initRankCamp();
        }

        GameServer.getInstance().sendActivityStatus(running, false);
    }
    /**
     * 结算
     */
    public void end()
    {
        if(status == E_ActivityCampStatus.CLEAR_ING)
            return;

        todayEndTime = DataFactory.currentTime;
        status = E_ActivityCampStatus.CLEAR_ING;

        if(matchFuture != null)
        {
            matchFuture.cancel(true);
            matchFuture = null;
        }

        LogUtils.warn("活动结束，通知所有参与的服务器 index -> " + index + " status -> " + status);

        GameServer.getInstance().sendActivityStatus(false, true);

        GameServer.getInstance().getActivityCampManager().save();

    }



    public MatchTeam addMatchTeam(E_MatchType matchType, E_BattleDetailType battleDetailType, CampPlayer player, MatchTempObject target)
    {
        if(getMatchTeam(player.getPlayerBase().getObjectIndex(), target.getBaseInfo().getObjectIndex()) != null)
            return null;

        MatchTeam matchTeam = new MatchTeam(matchType, battleDetailType, new MatchTempObject(matchType, player), target);
        matchTeamList.add(matchTeam);

        return matchTeam;
    }

    public MatchTeam getMatchTeam(String teamIndex)
    {
        for(MatchTeam matchTeam : matchTeamList)
        {
            if(matchTeam.getId().equals(teamIndex))
                return matchTeam;
        }
        return null;
    }

    public MatchTeam getMatchTeam(String playerIndex, String targetIndex)
    {
        for(MatchTeam matchTeam : matchTeamList)
        {
            if(matchTeam.getPlayer().getBaseInfo().getObjectIndex().equals(playerIndex) && matchTeam.getTarget().getBaseInfo().getObjectIndex().equals(targetIndex))
                return matchTeam;
        }
        return null;
    }


    public void campBattleResult(String playerIndex, BattleResultParamCampSingle singleResult, BattleResultParamCamp battleResult, E_ApplyCampActivityType applyType)
    {
        CampPlayer campPlayer = getPlayer(playerIndex);
        if(campPlayer == null)
            return;

        campBattleResult(campPlayer, singleResult, battleResult, applyType);
    }
    /**
     * 结算完成，更新数据
     * @param campPlayer
     * @param singleResult 单个玩家的结算结果
     */
    public void campBattleResult(CampPlayer campPlayer, BattleResultParamCampSingle singleResult, BattleResultParamCamp battleResult, E_ApplyCampActivityType applyType)
    {
        if(singleResult == null || campPlayer == null)
            return;

        if(singleResult.getPlayerBase() != null)
        {
            campPlayer.updatePlayerBase(singleResult.getPlayerBase());
            if(singleResult.getAddExploit() > 0)
            {
                JSONObject resultJson = updateRank(campPlayer.getPlayerBase().getServerId(), singleResult);
                GameServer.getInstance().sendRankInfo(resultJson);
                campPlayer.setPlayerStatus(E_PlayerStatus.WAIT_MATCH, DataFactory.currentTime);

                if(battleResult != null)
                {
                    //屏蔽结算时候奖励显示
                    battleResult.addReward(new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE, ConfigFactory.ASSET_EXPLOIT_KEY, singleResult.getAddExploit()));
                }
            }

            addMatchPlayer(campPlayer, applyType);
        }
        else
        {
            //没有复活次数了
            removePlayer(campPlayer);
        }

        if(battleResult != null)
        {
            battleResult.setLoserBeforeReviveCount(singleResult.getBeforeReviveCount());
            battleResult.setLoserAfterReviveCount(singleResult.getAfterReviveCount());
        }
    }


    public void setRewardTrue(int serverId){
        if (rankPlayerList == null || rankPlayerList.isEmpty()){
            return;
        }
        for (RankPlayer rankPlayer:rankPlayerList){
            if (serverId == rankPlayer.getServerId())
                rankPlayer.setReward(true);
        }
    }

    public List<String> getApplyPlayerList(int serverId)
    {
        List<String> list = new ArrayList<>();
        for(CampPlayer campPlayer : playerList)
        {
            if(campPlayer.getPlayerBase().getServerId() == serverId)
                list.add(campPlayer.getPlayerBase().getObjectIndex());
        }
        return list;
    }

    public List<String> getFirstCampPlayerList(int serverId)
    {
        List<String> list = new ArrayList<>();
        int camp = rankCampList.isEmpty() ? 0 : rankCampList.get(0).getCamp();
        if(camp == 0)
            return list;

        //还有复活次数的人
        for(CampPlayer player : playerList)
        {
            if(player.getPlayerBase().getServerId() == serverId && player.getPlayerBase().getCamp() == camp)
                list.add(player.getPlayerBase().getObjectIndex());
        }
        //没有复活次数的人
        for(CampRecordPlayer player : leavePlayerList)
        {
            if(player.getServerId() == serverId && player.getCamp() == camp)
                list.add(player.getObjectIndex());
        }
        return list;
    }

    public List<CampPlayer> getMatchPlayerList(int camp)
    {
        List<CampPlayer> list = new ArrayList<>();
        if(camp == 0)
        {
            for(Map.Entry<Integer, List<CampPlayer>> entry : campPlayerMap.entrySet())
            {
                list.addAll(entry.getValue());
            }
        }
        else
        {
            if(campPlayerMap.get(camp) != null)
                list.addAll(campPlayerMap.get(camp));
        }
        return list;
    }

    /**
     * 检测排行榜里面的数据是否是今天的
     * @return
     */
    public boolean checkRankIsToday()
    {
        String todayIndex = TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
        for(RankPlayer rankPlayer : rankPlayerList)
        {
            if(todayIndex.equals(TimeUtils.getFormatTime(rankPlayer.getCreateTime(), TimeUtils.YYYYMMDD)))
                return true;
        }

        return false;
    }

//    /**
//     * 修改报名和排行玩家的serverId
//     * @param mergeModel
//     * @throws Exception
//     */
//    public void updatePleyerServerId(MergeModel mergeModel) throws Exception{
//        int target = Integer.valueOf(mergeModel.getTarget());
//        String[] merge = mergeModel.getMerge().split(",");
//        List<Integer> mergeList = new ArrayList<>();
//        Arrays.stream(merge).forEach((m) -> mergeList.add(Integer.valueOf(m)));
//        for (CampPlayer player: playerList){
//            if (mergeList.contains(player.getPlayerBase().getServerId()))
//                player.getPlayerBase().setServerId(target);
//        }
//        for (RankPlayer player: rankPlayerList){
//            if (mergeList.contains(player.getServerId()))
//                player.setServerId(target);
//        }
//    }

//    public void addTempMatchList(String playerIndex, List<String> list)
//    {
//        tempMatchListMap.put(playerIndex, list);
//    }
//
//    public List<String> getTempMatchList(String playerIndex)
//    {
//        return tempMatchListMap.get(playerIndex);
//    }

    public List<RankCamp> getRankCampList() {
        return rankCampList;
    }

    public List<RankPlayer> getRankPlayerList() {
        return rankPlayerList;
    }

    public RankPlayer getMaxWinCountPlayer() {
        return maxWinCountPlayer;
    }

    public void setMaxWinCountPlayer(RankPlayer maxWinCountPlayer) {
        this.maxWinCountPlayer = maxWinCountPlayer;
    }

    public RankPlayer getMaxContinueWinPlayer() {
        return maxContinueWinPlayer;
    }

    public void setMaxContinueWinPlayer(RankPlayer maxContinueWinPlayer) {
        this.maxContinueWinPlayer = maxContinueWinPlayer;
    }

    public RankPlayer getMaxExploitPlayer() {
        return maxExploitPlayer;
    }

//    public Map<String, CampPlayer> getPlayerMap() {
//        return playerMap;
//    }

    public List<CampPlayer> getPlayerList() {
        return playerList;
    }

    public Map<Integer, List<CampPlayer>> getCampPlayerMap() {
        return campPlayerMap;
    }

    public E_ActivityCampStatus getStatus() {
        return status;
    }

    public ActivityCampModel getActivityCampModel() {
        return activityCampModel;
    }

    public void setActivityCampModel(ActivityCampModel activityCampModel) {
        this.activityCampModel = activityCampModel;
    }
}
